<template>
    <div>
       <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片列表 -->
         <el-card>
           <el-button type="primary" @click="roledialogVisible=true">添加角色</el-button>
             <el-table :data="rolesList" stripe border  row-key="id">
                <!-- prop用来指定渲染的字段 -->
                <el-table-column label="#" type="expand">
                  <template slot-scope="scope">
                    <!-- 循环生成一级权限 -->
                    <el-row v-for="(item,i) in scope.row.children" :key="item.id" :class="['bdbottom',i==0?'bdtop':'']" class="center">
                      <el-col :span="8">
                        <el-tag>{{item.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 嵌套二级和三级权限 -->
                      <el-col :span="16">
                        <el-row v-for="(item2,i2) in item.children" :key="item2.id" :class="i2==0?'':'bdtop'" class="center">
                          <el-col :span="6">
                           <el-tag type="success"> {{item2.authName}}</el-tag>
                           <i class="el-icon-caret-right"></i>
                            </el-col>
                          <el-col :span="18">
                            <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRoles(scope.row,item3.id)">{{item3.authName}}</el-tag>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit"  size="mini" >编辑</el-button>
             <el-button type="danger" icon="el-icon-delete"  size="mini" @click="roleDelete(scope.row.id)">删除</el-button>
             <el-button type="warning" icon="el-icon-setting"  size="mini" @click="showDialogVisible(scope.row)">分配权限</el-button>
            
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限对话框 -->
        <el-dialog
          title="分配权限"
          :visible.sync="setDialogVisible"
          width="30%" @close="setRightsClose">
          <el-tree ref="tree" :default-checked-keys="defaultKeys" :data="rightsList" :props="defaultProps" show-checkbox default-expand-all node-key="id" ></el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRights">确 定</el-button>
          </span>
        </el-dialog>
       <!-- 添加角色对话框 -->
       <el-dialog
      title="添加用户"
      :visible.sync="roledialogVisible"
      width="30%" @close="addRoleClose">
     <!-- 主体内容 -->
     <el-form ref="addRolesRef" :model="addRolesForm" :rules="addRolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
     </el-form>
     <!-- 尾部内容 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRolesForm">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList:[],
      rightsList:[],//所有权限列表
      setDialogVisible:false,
      defaultProps:{
        label:'authName',
        children:'children'
      },
        // 设置默认选中
      defaultKeys:[],
      rolesId:0,
      // 添加角色form对象
      addRolesForm:{
        roleName:'',
        roleDesc:''
      },
      addRolesRules:{
        roleName:[
            { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 显示添加角色对话框
      roledialogVisible:false
    }
  },

  created() {
    this.getRolesList()
  },

  methods: {
    //   获取权限列表
    async getRolesList(){
        const {data:res}=await this.$axios.get('roles')
        if(res.meta.status!=200)return this.$message.error('获取列表失败')
        this.rolesList=res.data;
       
    },
    removeRoles(row,id){
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res}=await this.$axios.delete(`roles/${row.id}/rights/${id}`)
         
          if(res.meta.status!=200)return this.$message.error('删除失败')
          row.children=res.data;
          this.$message.success('删除成功!');
        }).catch(() => {
          this.$message('已取消删除');          
        });
    },
    // 显示权限列表
    async showDialogVisible(row){
      this.rolesId=row.id;
      this.setDialogVisible = true;
      const {data:res}=await this.$axios.get('rights/tree')
      if(res.meta.status!=200)return this.$message.error('数据获取失败')
      this.rightsList=res.data;
      this.getAllKeys(row);
    },
    // 定义递归，获取第三层id
    getAllKeys(row){
      if(!row.children)return this.defaultKeys.push(row.id)
      row.children.forEach(item => {
        this.getAllKeys(item)
      });
    },
    // 监听关闭分配权限对话框
    setRightsClose(){
      this.defaultKeys=[]
    },
    // 给用户分配权限
    async setRights(){
      // 发送请求
      // 1：角色id
      // 2：所有授权权限id（获取所有勾选的权限id）
      // 获取所有全选节点
      const keys=this.$refs.tree.getCheckedKeys()
      // 获取所有半选节点
      const halfkeys=this.$refs.tree.getHalfCheckedKeys()
      const allkeys=[...keys,...halfkeys].join(',')
      // 发送请求
      const {data:res}=await this.$axios.post(`roles/${this.rolesId}/rights`,{rids:allkeys})
      
      if(res.meta.status!=200)return this.$message.error('请求失败')
      this.$message.success('分配成功')
      this.getRolesList()
      this.setDialogVisible = false
    },
    // 提交添加角色
   submitRolesForm(){
      this.$refs.addRolesRef.validate(async (flag)=>{
        if(!flag)return this.$message.error('角色名称验证失败')
        const {data:res}=await this.$axios.post('roles',this.addRolesForm)
        if(res.meta.status!=201)return this.$message.error('添加角色失败')
          this.$message.success('成功添加角色')
          this.getRolesList();
          this.roledialogVisible=false;
          })
   
    },
    //监听关闭添加角色对话框
    addRoleClose(){
     this.$refs.addRolesRef.resetFields();
    },
    //删除角色
    async roleDelete(id){
      console.log(id);
      
    const {data:res}=await this.$axios.delete(`roles/${id}`)
    if(res.meta.status!=200)return this.$message.error('删除角色失败')
      this.$message.success('成功删除角色')
      this.getRolesList();
    }
  }
};
</script>

<style scoped lang='less'>
.el-tag{
  margin: 7px;
}
.bdbottom{
  border-bottom: 1px solid #EBEEF5;
}
.bdtop{
  border-top: 1px solid #EBEEF5;
}
.center{
  display: flex;
  align-items: center;
}
</style>
